/**
 * Created by zhaojm on 15/3/28.
 */
// 子弹
game.Bullet = game.RoleProtocol.extend({

    _velocityX : null,
    _velocityY : null,
    _layer : null,
    _HP : null,
    ctor:function(speed, weapon){
        this._super();

        this._active = true;
        this._velocityX = 0;
        this._velocityY = -speed;
        this._HP = 1;

        this._sprite = new cc.Sprite(weapon);
        this._sprite.setBlendFunc(gl.SRC_ALPHA, gl.ONE);
    },

    addToLayer : function(layer){
        this._layer = layer;
        layer.addChild(this._sprite);

    },
    removeFromLayer:function(){
        this._layer.play_bullet.remove(this);
        this._layer.enemy_bullet.remove(this);
        this._sprite.removeFromParent();
    },

    setPosition:function(pos){
        this._sprite.setPosition(pos);
    },

    destroy : function(){

        var explode = new cc.Sprite(res.hit_jpg);
        explode.setBlendFunc(gl.SRC_ALPHA, gl.ONE);
        explode.setPosition(this._sprite.getPosition());
        explode.setRotation(Math.random() * 360);
        explode.setScale(0.75);
        this._layer.addChild(explode, 9999);

        this.removeFromLayer();

        var removeExplode =  cc.CallFunc.create(this.removeExplode);
        explode.runAction(cc.ScaleBy.create(0.3, 2, 2));
        explode.runAction(cc.Sequence.create(cc.FadeOut.create(0.3), removeExplode));
    },

    removeExplode:function(pSender){
        pSender.removeFromParent();
    },

    hurt : function(){
        this._HP--;
    },
    collideRect : function(){
        var pos = this._sprite.getPosition();
        return cc.rect(pos.x - 3, pos.y - 3, 6, 6);
    },

    update:function(dt){
        var size = cc.winSize;
        var position = this._sprite.getPosition();
        position.x -= this._velocityX * dt;
        position.y -= this._velocityY * dt;
        this._sprite.setPosition(position);

        if (this._HP <= 0) {
            this.destroy();
            return;
        }
        var screenRect = cc.rect(0, 0,  size.width, size.height + 10);
        if((!cc.rectIntersectsRect(screenRect, this.collideRect()))){
            this.removeFromLayer();
        }

    }

});

game.Bullet.createShipBullet = function(){
    return new game.Bullet(game.Config.ship.bulletSpeed, game.Config.ship.bulletType);
};
game.Bullet.createEnemyBullet = function(){
    return new game.Bullet(game.Config.enemy.bulletSpeed, game.Config.enemy.bulletType);
};